<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航栏 -->
    <header class="sticky top-0 z-50 bg-white shadow-md transition-all duration-300">
      <div class="container mx-auto px-4">
        <div class="flex items-center justify-between h-16 md:h-20">
          <!-- Logo -->
          <div class="flex items-center">
            <router-link to="/home" class="flex items-center">
              <i class="fas fa-book text-primary text-2xl md:text-3xl mr-2"></i>
              <span class="text-xl md:text-2xl font-bold text-primary" style="font-weight: 700;">书香阁</span>
            </router-link>
          </div>

          <!-- 主导航 - 桌面版 -->
          <nav class="hidden md:flex items-center space-x-8">
            <router-link to="/home" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">首页</router-link>
            <router-link to="/category" class="font-medium text-primary border-b-2 border-primary py-1">分类</router-link>
            <router-link to="/bestseller" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">畅销榜</router-link>
            <router-link to="/news" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">资讯</router-link>
          </nav>

          <!-- 搜索框 -->
          <div class="hidden md:flex items-center flex-1 max-w-md mx-8">
            <div class="relative w-full flex">
              <el-input
                v-model="searchKeyword"
                placeholder="请输入您喜欢的商品"
                class="search-input flex-1"
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <i class="fas fa-search text-gray-400"></i>
                </template>
              </el-input>
              <button
                @click="handleSearch"
                class="search-button ml-2 px-4 py-2 text-white rounded-full transition-colors flex items-center justify-center"
              >
                <i class="fas fa-search"></i>
              </button>
            </div>
          </div>

          <!-- 用户工具栏 -->
          <div class="flex items-center space-x-4">
            <button class="relative p-2 text-gray-600 hover:text-primary transition-colors">
              <i class="fas fa-bell text-lg"></i>
              <span class="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full"></span>
            </button>
            <button
              @click="goToCart"
              class="relative p-2 text-gray-600 hover:text-primary transition-colors"
            >
              <i class="fas fa-shopping-cart text-lg"></i>
              <span class="absolute -top-1 -right-1 bg-primary text-white text-xs rounded-full w-5 h-5 flex items-center justify-center cart-badge">{{ cartCount }}</span>
            </button>

            <!-- 用户下拉菜单 -->
            <el-dropdown @command="handleCommand">
              <span class="el-dropdown-link cursor-pointer flex items-center">
                <el-avatar :size="32" :src="getImageUrl(userStore.userInfo?.avatar)">
                  <i class="fas fa-user"></i>
                </el-avatar>
                <span class="hidden md:block ml-2 text-gray-600">{{ userStore.userInfo?.username }}</span>
                <i class="fas fa-chevron-down ml-1 text-gray-400"></i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人资料</el-dropdown-item>
                  <el-dropdown-item command="orders">我的订单</el-dropdown-item>
                  <el-dropdown-item command="settings">设置</el-dropdown-item>
                  <el-dropdown-item v-if="userStore.isAdmin" command="admin" divided>
                    <i class="fas fa-cog mr-2"></i>管理后台
                  </el-dropdown-item>
                  <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <!-- 移动端菜单按钮 -->
            <button @click="toggleMobileMenu" class="md:hidden p-2 text-gray-600 hover:text-primary transition-colors">
              <i class="fas fa-bars text-xl"></i>
            </button>
          </div>
        </div>

        <!-- 移动端搜索框 -->
        <div class="md:hidden pb-4">
          <div class="flex">
            <el-input
              v-model="searchKeyword"
              placeholder="请输入您喜欢的商品"
              class="search-input flex-1"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <i class="fas fa-search text-gray-400"></i>
              </template>
            </el-input>
            <button
              @click="handleSearch"
              class="search-button ml-2 px-4 py-2 text-white rounded-full transition-colors flex items-center justify-center"
            >
              <i class="fas fa-search"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- 移动端导航菜单 -->
      <div v-show="showMobileMenu" class="md:hidden bg-white border-t border-gray-100 shadow-lg">
        <div class="container mx-auto px-4 py-3 space-y-3">
          <router-link to="/home" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">首页</router-link>
          <router-link to="/category" class="block py-2 px-3 rounded-lg bg-primary/10 text-primary font-medium">分类</router-link>
          <router-link to="/bestseller" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">畅销榜</router-link>
          <router-link to="/news" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">资讯</router-link>
        </div>
      </div>
    </header>

    <!-- 主要内容 -->
    <main class="container mx-auto px-4 py-6">
      <!-- 面包屑导航 -->
      <nav class="mb-6">
        <ol class="flex items-center space-x-2 text-sm text-gray-600">
          <li>
            <router-link to="/home" class="hover:text-primary transition-colors">首页</router-link>
          </li>
          <li><i class="fas fa-chevron-right text-xs"></i></li>
          <li class="text-primary font-medium">图书分类</li>
        </ol>
      </nav>

      <!-- 分类页面标题 -->
      <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-800 mb-2">图书分类</h1>
        <p class="text-gray-600">发现您喜爱的图书类型，探索阅读的无限可能</p>
      </div>

      <div class="flex flex-col lg:flex-row gap-6">
        <!-- 左侧筛选栏 -->
        <aside class="lg:w-64 flex-shrink-0">
          <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6 sticky top-24">
            <!-- 分类筛选 -->
            <div class="mb-6">
              <h3 class="font-bold text-gray-800 mb-4 flex items-center">
                <i class="fas fa-list text-primary mr-2"></i>
                图书分类
              </h3>
              <ul class="space-y-2">
                <li v-for="category in categories" :key="category.id">
                  <button
                    @click="selectCategory(category.id)"
                    :class="[
                      'w-full text-left px-3 py-2 rounded-lg transition-colors',
                      selectedCategory === category.id 
                        ? 'bg-primary/10 text-primary font-medium' 
                        : 'hover:bg-gray-100 text-gray-600'
                    ]"
                  >
                    <i :class="category.icon" class="mr-2 text-sm"></i>
                    {{ category.name }}
                  </button>
                </li>
              </ul>
            </div>

            <!-- 价格筛选 -->
            <div class="mb-6">
              <h3 class="font-bold text-gray-800 mb-4 flex items-center">
                <i class="fas fa-tag text-primary mr-2"></i>
                价格范围
              </h3>
              <div class="space-y-2">
                <button
                  v-for="priceRange in priceRanges"
                  :key="priceRange.id"
                  @click="selectPriceRange(priceRange.id)"
                  :class="[
                    'w-full text-left px-3 py-2 rounded-lg transition-colors text-sm',
                    selectedPriceRange === priceRange.id 
                      ? 'bg-primary/10 text-primary font-medium' 
                      : 'hover:bg-gray-100 text-gray-600'
                  ]"
                >
                  {{ priceRange.label }}
                </button>
              </div>
            </div>

            <!-- 排序方式 -->
            <div>
              <h3 class="font-bold text-gray-800 mb-4 flex items-center">
                <i class="fas fa-sort text-primary mr-2"></i>
                排序方式
              </h3>
              <el-select v-model="sortBy" placeholder="选择排序方式" class="w-full">
                <el-option label="默认排序" value="default"></el-option>
                <el-option label="价格从低到高" value="price_asc"></el-option>
                <el-option label="价格从高到低" value="price_desc"></el-option>
                <el-option label="销量最高" value="sales"></el-option>
                <el-option label="最新上架" value="newest"></el-option>
              </el-select>
            </div>
          </div>
        </aside>

        <!-- 右侧图书列表 -->
        <div class="flex-1">
          <!-- 结果统计和视图切换 -->
          <div class="flex items-center justify-between mb-6 bg-white rounded-xl shadow-sm border border-gray-100 p-4">
            <div class="text-gray-600">
              共找到 <span class="text-primary font-bold">{{ filteredBooks.length }}</span> 本图书
            </div>
            <div class="flex items-center space-x-2">
              <button
                @click="viewMode = 'grid'"
                :class="[
                  'p-2 rounded-lg transition-colors',
                  viewMode === 'grid' ? 'bg-primary text-white' : 'text-gray-600 hover:bg-gray-100'
                ]"
              >
                <i class="fas fa-th"></i>
              </button>
              <button
                @click="viewMode = 'list'"
                :class="[
                  'p-2 rounded-lg transition-colors',
                  viewMode === 'list' ? 'bg-primary text-white' : 'text-gray-600 hover:bg-gray-100'
                ]"
              >
                <i class="fas fa-list"></i>
              </button>
            </div>
          </div>

          <!-- 图书网格视图 -->
          <div v-if="viewMode === 'grid'" class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-4 xl:grid-cols-5 gap-4 mb-8">
            <div
              v-for="book in paginatedBooks"
              :key="book.id"
              @click="goToBookDetail(book.id)"
              class="bg-white rounded-xl overflow-hidden shadow-sm hover:shadow-lg transition-all duration-300 transform hover:-translate-y-1 border border-gray-100 cursor-pointer"
            >
              <div class="relative">
                <img
                  :src="book.cover"
                  :alt="book.title"
                  class="w-full h-48 object-cover"
                >
                <div v-if="book.tag" :class="`absolute top-3 left-3 text-white text-xs font-bold px-2 py-1 rounded ${book.tagColor}`">
                  {{ book.tag }}
                </div>
              </div>
              <div class="p-3">
                <h3 class="font-bold text-sm mb-1 line-clamp-1 text-gray-800">{{ book.title }}</h3>
                <p class="text-gray-500 text-xs mb-1 line-clamp-1">{{ book.author }}</p>
                <div class="flex items-center justify-between">
                  <span class="text-primary font-bold text-sm">¥{{ book.price }}</span>
                  <button
                    @click.stop="addToCart(book)"
                    class="w-8 h-8 rounded-full bg-primary/10 text-primary flex items-center justify-center hover:bg-primary hover:text-white transition-colors"
                  >
                    <i class="fas fa-shopping-cart text-sm"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>

          <!-- 图书列表视图 -->
          <div v-else class="space-y-4 mb-8">
            <div
              v-for="book in paginatedBooks"
              :key="book.id"
              @click="goToBookDetail(book.id)"
              class="bg-white rounded-xl overflow-hidden shadow-sm hover:shadow-lg transition-all duration-300 border border-gray-100 cursor-pointer"
            >
              <div class="flex p-4">
                <div class="relative flex-shrink-0 w-24 h-32 mr-4">
                  <img
                    :src="book.cover"
                    :alt="book.title"
                    class="w-full h-full object-cover rounded-lg"
                  >
                  <div v-if="book.tag" :class="`absolute top-2 left-2 text-white text-xs font-bold px-2 py-1 rounded ${book.tagColor}`">
                    {{ book.tag }}
                  </div>
                </div>
                <div class="flex-1">
                  <h3 class="font-bold text-lg mb-2 text-gray-800">{{ book.title }}</h3>
                  <p class="text-gray-500 text-sm mb-2">作者：{{ book.author }}</p>
                  <p class="text-gray-600 text-sm mb-3 line-clamp-2">{{ book.description }}</p>
                  <div class="flex items-center justify-between">
                    <span class="text-primary font-bold text-xl">¥{{ book.price }}</span>
                    <button
                      @click.stop="addToCart(book)"
                      class="px-4 py-2 bg-primary/10 text-primary rounded-full hover:bg-primary hover:text-white transition-colors"
                    >
                      <i class="fas fa-shopping-cart mr-1"></i>
                      加入购物车
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div class="flex justify-center">
            <el-pagination
              v-model:current-page="currentPage"
              :page-size="pageSize"
              :total="totalBooks"
              layout="prev, pager, next, jumper"
              @current-change="handlePageChange"
              class="pagination-custom"
            />
          </div>
        </div>
      </div>
    </main>

    <!-- 底部页脚 -->
    <footer class="bg-gray-900 text-white py-10">
      <div class="container mx-auto px-4">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
          <!-- 关于我们 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">关于书香阁</h3>
            <p class="text-gray-400 text-sm">
              书香阁是专业的网上书店，提供超过10万种图书在线购买，支持快递配送和自提服务，让阅读触手可及。
            </p>
            <div class="flex space-x-4 mt-4">
              <a href="#" class="text-gray-400 hover:text-primary"><i class="fab fa-weixin text-xl"></i></a>
              <a href="#" class="text-gray-400 hover:text-primary"><i class="fab fa-weibo text-xl"></i></a>
              <a href="#" class="text-gray-400 hover:text-primary"><i class="fab fa-qq text-xl"></i></a>
              <a href="#" class="text-gray-400 hover:text-primary"><i class="fas fa-envelope text-xl"></i></a>
            </div>
          </div>

          <!-- 快捷链接 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">快捷链接</h3>
            <ul class="space-y-2 text-sm">
              <li><router-link to="/category" class="text-gray-400 hover:text-primary">分类浏览</router-link></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">热门排行</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">最新上架</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">特价促销</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">读者推荐</a></li>
            </ul>
          </div>

          <!-- 客户服务 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">客户服务</h3>
            <ul class="space-y-2 text-sm">
              <li><a href="#" class="text-gray-400 hover:text-primary">常见问题</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">配送方式</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">支付方式</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">退换政策</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">联系我们</a></li>
            </ul>
          </div>

          <!-- 联系方式 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">联系我们</h3>
            <ul class="space-y-3 text-sm">
              <li class="flex items-start">
                <i class="fas fa-map-marker-alt text-primary mt-1 mr-3"></i>
                <span class="text-gray-400">北京市朝阳区建国路88号</span>
              </li>
              <li class="flex items-center">
                <i class="fas fa-phone text-primary mr-3"></i>
                <span class="text-gray-400">400-800-1234</span>
              </li>
              <li class="flex items-center">
                <i class="fas fa-envelope text-primary mr-3"></i>
                <span class="text-gray-400">service@bookstore.com</span>
              </li>
              <li class="flex items-center">
                <i class="fas fa-clock text-primary mr-3"></i>
                <span class="text-gray-400">周一至周日 9:00-22:00</span>
              </li>
            </ul>
          </div>
        </div>

        <!-- 版权信息 -->
        <div class="border-t border-gray-800 mt-8 pt-8 flex flex-col md:flex-row justify-between items-center">
          <div class="text-gray-500 text-sm mb-4 md:mb-0">
            © {{ new Date().getFullYear() }} 书香阁 版权所有 | 京ICP备12345678号
          </div>
          <div class="flex space-x-4">
            <a href="#" class="text-gray-500 text-sm hover:text-primary">隐私政策</a>
            <a href="#" class="text-gray-500 text-sm hover:text-primary">使用条款</a>
            <a href="#" class="text-gray-500 text-sm hover:text-primary">网站地图</a>
          </div>
        </div>
      </div>
    </footer>

    <!-- 回到顶部按钮 -->
    <BackToTop />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useCartStore } from '@/stores/cart'
import { ElMessage } from 'element-plus'
import BackToTop from '@/components/BackToTop.vue'
import { bookAPI } from '@/api/book.js'

const router = useRouter()
const userStore = useUserStore()
const cartStore = useCartStore()

// 响应式数据
const searchKeyword = ref('')
const showMobileMenu = ref(false)
const selectedCategory = ref(null)
const selectedPriceRange = ref(null)
const sortBy = ref('default')
const viewMode = ref('grid')
const currentPage = ref(1)
const pageSize = ref(20)

// 计算购物车数量，使用cartStore
const cartCount = computed(() => cartStore.cartCount)

// 图书分类数据
const categories = reactive([
  { id: null, name: '全部分类', icon: 'fas fa-th-large' }
])

// 分类图标映射
const categoryIconMap = {
  '外语学习': 'fas fa-language',
  '哲学宗教': 'fas fa-brain',
  '儿童读物': 'fas fa-child',
  '科学技术': 'fas fa-flask',
  '文学小说': 'fas fa-heart',
  '教育教材': 'fas fa-graduation-cap',
  '计算机': 'fas fa-laptop-code',
  '历史': 'fas fa-history',
  '艺术': 'fas fa-palette',
  '经济管理': 'fas fa-chart-line',
  '医学': 'fas fa-stethoscope',
  '法律': 'fas fa-balance-scale'
}

// 价格范围数据
const priceRanges = reactive([
  { id: null, label: '全部价格' },
  { id: 1, label: '0-30元', min: 0, max: 30 },
  { id: 2, label: '30-60元', min: 30, max: 60 },
  { id: 3, label: '60-100元', min: 60, max: 100 },
  { id: 4, label: '100-200元', min: 100, max: 200 },
  { id: 5, label: '200元以上', min: 200, max: Infinity }
])

// 图书数据
const books = reactive([])
const loading = ref(false)
const totalBooks = ref(0)

// 加载图书数据
const loadBooks = async () => {
  loading.value = true
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value
    }

    // 如果有搜索关键词，添加搜索参数
    if (searchKeyword.value.trim()) {
      params.title = searchKeyword.value.trim()
    }

    // 如果选择了分类，添加分类筛选（仅在调用searchBooks时使用）
    if (selectedCategory.value !== null && selectedCategory.value !== undefined) {
      params.categoryId = selectedCategory.value
    }

    let response
    if (selectedCategory.value !== null && selectedCategory.value !== undefined) {
      // 按分类获取图书
      response = await bookAPI.getBooksByCategory(selectedCategory.value, params)
    } else {
      // 搜索所有图书（不传分类ID参数）
      delete params.categoryId
      response = await bookAPI.searchBooks(params)
    }

    if (response && response.code === 200) {
      const booksData = response.data.records.map(book => ({
        ...book,
        price: parseFloat(book.price || 0),
        cover: getImageUrl(book.cover) || '/src/assets/images/ggbond.png',
        tag: book.tags && book.tags.length > 0 ? book.tags[0].name : '图书',
        tagColor: book.tags && book.tags.length > 0 ? book.tags[0].tagColor : 'bg-blue-500',
        categoryId: book.categoryId,
        sales: book.sales || 0
      }))

      books.splice(0, books.length, ...booksData)
      totalBooks.value = response.data.total
    }
  } catch (error) {
    console.error('加载图书数据失败:', error)
    ElMessage.error('加载图书数据失败，请刷新页面重试')
  } finally {
    loading.value = false
  }
}

// 计算属性 - 前端价格筛选和排序
const filteredBooks = computed(() => {
  let result = [...books]

  // 按价格筛选（前端筛选）
  if (selectedPriceRange.value !== null) {
    const priceRange = priceRanges.find(range => range.id === selectedPriceRange.value)
    if (priceRange) {
      result = result.filter(book => book.price >= priceRange.min && book.price <= priceRange.max)
    }
  }

  // 排序（前端排序）
  switch (sortBy.value) {
    case 'price_asc':
      result = result.sort((a, b) => a.price - b.price)
      break
    case 'price_desc':
      result = result.sort((a, b) => b.price - a.price)
      break
    case 'sales':
      result = result.sort((a, b) => b.sales - a.sales)
      break
    case 'newest':
      result = result.sort((a, b) => b.id - a.id)
      break
    default:
      // 默认排序保持原顺序
      break
  }

  return result
})

// 由于后端已经处理分页，直接使用筛选后的结果
const paginatedBooks = computed(() => {
  return filteredBooks.value
})

// 方法
const toggleMobileMenu = () => {
  showMobileMenu.value = !showMobileMenu.value
}

const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    currentPage.value = 1
    loadBooks()
  } else {
    ElMessage.warning('请输入搜索关键词')
  }
}

const selectCategory = (categoryId) => {
  selectedCategory.value = categoryId
  currentPage.value = 1 // 重置到第一页
  loadBooks() // 重新加载数据
}

const selectPriceRange = (rangeId) => {
  selectedPriceRange.value = rangeId
  currentPage.value = 1 // 重置到第一页
  // 价格筛选在前端进行，不需要重新加载数据
}

const handlePageChange = (page) => {
  currentPage.value = page
  loadBooks() // 加载新页面数据
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 添加到购物车方法修改
const addToCart = async (book) => {
  try {
    await cartStore.addToCart(book)
    // 消息提示已在store中处理，这里不需要重复提示
  } catch (error) {
    console.error('添加到购物车失败:', error)
  }
}

const goToBookDetail = (bookId) => {
  router.push(`/book/${bookId}`)
}

const goToCart = () => {
  router.push('/cart')
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'orders':
      router.push('/orders')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'admin':
      router.push('/admin')
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 处理登出
const handleLogout = () => {
  userStore.logout()
  ElMessage.success('已退出登录')
  router.push('/login')
}

// 获取图片URL
const getImageUrl = (url) => {
  if (!url) return ''

  // 如果是完整的URL，直接返回
  if (url.startsWith('http')) {
    return url
  }

  // 如果是上传的文件路径
  if (url.startsWith('/uploads/')) {
    return `http://localhost:8081/api${url}`
  }

  // 如果是静态资源路径
  if (url.startsWith('/assets/')) {
    return `http://localhost:8081/api${url}`
  }

  // 其他情况，添加API前缀
  return `/api${url}`
}

// 加载分类数据
const loadCategories = async () => {
  try {
    const response = await bookAPI.getCategories()
    if (response && response.code === 200) {
      const categoryData = response.data.map(category => ({
        ...category,
        icon: categoryIconMap[category.name] || 'fas fa-book'
      }))
      // 保留"全部分类"选项，然后添加从数据库获取的分类
      categories.splice(1, categories.length - 1, ...categoryData)
    }
  } catch (error) {
    console.error('加载分类数据失败:', error)
    // 如果加载失败，使用默认分类数据
    const defaultCategories = [
      { id: 1, name: '外语学习', icon: 'fas fa-language' },
      { id: 2, name: '哲学宗教', icon: 'fas fa-brain' },
      { id: 3, name: '儿童读物', icon: 'fas fa-child' },
      { id: 4, name: '科学技术', icon: 'fas fa-flask' },
      { id: 5, name: '文学小说', icon: 'fas fa-heart' },
      { id: 6, name: '教育教材', icon: 'fas fa-graduation-cap' }
    ]
    categories.splice(1, categories.length - 1, ...defaultCategories)
  }
}

// 生命周期
onMounted(async () => {
  // 加载分类数据
  await loadCategories()
  // 初始化时选择全部分类
  selectedCategory.value = null
  selectedPriceRange.value = null
  // 加载图书数据
  await loadBooks()
})
</script>

<style scoped>
/* 自定义样式 */
:root {
  --primary: #FF6B8A;
  --primary-light: #FFB3C6;
  --primary-dark: #E55A7A;
  --secondary: #FFF0F3;
  --accent: #FF8FA3;
  --success: #4CAF50;
  --warning: #FF9800;
  --info: #2196F3;
  --dark: #2D3748;
  --gray: #718096;
  --light-gray: #F7FAFC;
  --white: #FFFFFF;
}

.el-dropdown-link {
  display: flex;
  align-items: center;
  color: #606266;
  transition: color 0.3s ease;
}

.el-dropdown-link:hover {
  color: var(--primary);
}

/* 搜索框样式 */
.search-input :deep(.el-input__wrapper) {
  border-radius: 9999px;
  border: 1px solid #d1d5db;
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper):hover {
  border-color: var(--primary);
}

.search-input :deep(.el-input__wrapper.is-focus) {
  border-color: var(--primary);
  box-shadow: 0 0 0 2px rgba(255, 107, 139, 0.2);
}

/* 搜索按钮样式 */
.search-button {
  background-color: #FF6B8B !important;
}

.search-button:hover {
  background-color: rgba(255, 107, 139, 0.8) !important;
}

/* 文本截断 */
.line-clamp-1 {
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 主题色定义 */
.text-primary {
  color: rgb(255, 107, 139) !important;
}

.bg-primary {
  background-color: #FF6B8B !important;
}

.border-primary {
  border-color: #FF6B8B !important;
}

.text-secondary {
  color: var(--secondary);
}

.bg-secondary\/30 {
  background-color: rgba(255, 209, 220, 0.3);
}

.text-accent {
  color: var(--accent);
}

.text-dark {
  color: var(--dark);
}

.hover\:text-primary:hover {
  color: #FF6B8B !important;
}

.border-primary\/30 {
  border-color: rgba(255, 107, 138, 0.3);
}

/* 购物车按钮样式 */
.bg-primary\/10 {
  background-color: rgba(255, 107, 139, 0.1) !important;
}

.hover\:bg-primary:hover {
  background-color: #FF6B8B !important;
}

.hover\:text-white:hover {
  color: white !important;
}

/* 自定义分页样式 */
.pagination-custom :deep(.el-pagination) {
  justify-content: center;
}

.pagination-custom :deep(.el-pager li) {
  border-radius: 8px;
  margin: 0 2px;
  transition: all 0.3s ease;
}

.pagination-custom :deep(.el-pager li.is-active) {
  background-color: var(--primary);
  border-color: var(--primary);
}

.pagination-custom :deep(.btn-prev),
.pagination-custom :deep(.btn-next) {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.pagination-custom :deep(.btn-prev:hover),
.pagination-custom :deep(.btn-next:hover) {
  color: var(--primary);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .container {
    padding-left: 1rem;
    padding-right: 1rem;
  }
}

/* 卡片悬停效果 */
.card-hover {
  transition: all 0.3s ease;
}

.card-hover:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

/* 自定义选择器样式 */
:deep(.el-select .el-input__wrapper) {
  border-radius: 8px;
  transition: all 0.3s ease;
}

:deep(.el-select .el-input__wrapper):hover {
  border-color: var(--primary);
}

:deep(.el-select .el-input__wrapper.is-focus) {
  border-color: var(--primary);
  box-shadow: 0 0 0 2px rgba(255, 107, 139, 0.2);
}

.cart-badge {
  z-index: 10;
  transform: translate(25%, -25%);
  min-width: 18px;
  height: 18px;
}
</style>
